/* eslint-disable max-len */
import {
    View, Text, TouchableOpacity, Alert,
} from 'react-native';
import React, {
    useState, useEffect, forwardRef, useImperativeHandle,
} from 'react';
import { AudioRecorder, AudioUtils } from 'react-native-audio';
import Sound from 'react-native-sound';
import { Toast, WhiteSpace } from '@ant-design/react-native';
import Feather from 'react-native-vector-icons/Feather';
import PropTypes from 'prop-types';
import Slider from '@react-native-community/slider';
import styles from './styles';

const Recorder = forwardRef(({ setRecordUri, recordUri }, ref) => {
    const [hasPermission, setHasPermission] = useState(undefined);
    // eslint-disable-next-line no-unused-vars
    const [audioPath, setAudioPath] = useState(`${AudioUtils.DocumentDirectoryPath}/quick_audio_${new Date().getTime()}.aac`);
    const [stop, setStop] = useState(false);
    const [recording, setRecording] = useState(false);
    const [currentTime, setCurrentTime] = useState(0);
    const [duration, setDuration] = useState(0);
    const [isExist, setIsExist] = useState(false);
    const [playTime, setPlayTime] = useState(0);
    const [whoosh2, setWhoosh2] = useState(() => {});
    const prepareRecordingPath = (path) => {
        const option = {
            SampleRate: 44100.0, // 采样率
            Channels: 2, // 通道
            AudioQuality: 'High', // 音质
            AudioEncoding: 'aac', // 音频编码 aac
            OutputFormat: 'mpeg_4', // 输出格式
            MeteringEnabled: false, // 是否计量
            MeasurementMode: false, // 测量模式
            AudioEncodingBitRate: 32000, // 音频编码比特率
            IncludeBase64: true, // 是否是base64格式
            AudioSource: 0, // 音频源
        };
        AudioRecorder.prepareRecordingAtPath(path, option);
        setAudioPath(path);
    };
    const getAudioAuthorize = () => {
        AudioRecorder.requestAuthorization()
            .then((isAuthor) => {
                if (!isAuthor) {
                    Alert.alert('APP需要使用录音，请打开录音权限允许APP使用');
                }
                setHasPermission(isAuthor);
                prepareRecordingPath(audioPath);
                // 录音进展
                AudioRecorder.onProgress = (data) => {
                    setCurrentTime(Math.ceil(data.currentTime));
                };
                // 完成录音
                AudioRecorder.onFinished = (data) => {
                    // data 录音数据，可以在此存储需要传给接口的路径数据
                    setRecordUri(data.audioFileURL);
                };
            });
    };
    useEffect(() => {
        getAudioAuthorize();
        if (recordUri !== '') {
            setIsExist(true);
        }
    }, []);
    const getAudioTimeString = (seconds) => {
        const h = parseInt(seconds / (60 * 60), 10);
        const m = parseInt((seconds % (60 * 60)) / 60, 10);
        const s = parseInt(seconds % 60, 10);
        const timeH = h < 10 ? `0${h}` : h;
        const timeM = m < 10 ? `0${m}` : m;
        const timeS = s < 10 ? `0${s}` : s;
        return (`${timeH}:${timeM}:${timeS}`);
    };
    const playTimeString = getAudioTimeString(playTime);
    const currentTimeString = getAudioTimeString(currentTime);
    const durationString = getAudioTimeString(duration);
    // 开始录音
    const handleStartAudio = async () => {
        if (!hasPermission) {
            Toast.info('APP需要使用录音，请打开录音权限允许APP使用', 1, undefined, false);
        }
        Toast.info('录音开始', 1, undefined, false);
        if (stop) {
        // 初始化录音
            prepareRecordingPath(audioPath);
        }
        try {
            await AudioRecorder.startRecording();
            setRecording(true);
        } catch (err) {
            Toast.info('录音失败', 1, undefined, false);
        }
    };
    // 停止录音
    const handleStopAudio = async () => {
        Toast.info('录音结束', 1, undefined, false);
        try {
            await AudioRecorder.stopRecording();
            setStop(true);
            setRecording(false);
            setIsExist(true);
        } catch (error) {
            Toast.info('录音失败', 1, undefined, false);
        }
    };
    // 播放录音
    // const handlePlayAudio = async () => {
    //     Toast.info('正在播放', 1, undefined, false);
    //     const whoosh = new Sound(recordUri !== '' ? recordUri : audioPath, '', (err) => {
    //         if (err) {
    //             Toast.info('加载音频失败', 1, undefined, false);
    //         }
    //         setDuration(whoosh.getDuration());
    //         // whoosh.setCurrentTime(0);
    //         whoosh.play((success) => {
    //             if (success) {
    //                 Toast.info('播放完毕', 1, undefined, false);
    //             } else {
    //                 Toast.info('播放失败', 1, undefined, false);
    //             }
    //         });
    //         const timeout = setInterval(() => {
    //             if (whoosh && whoosh.isLoaded()) {
    //                 whoosh.getCurrentTime((seconds, isPlaying) => {
    //                     if (!isPlaying) {
    //                         setPlayTime(seconds);
    //                         clearInterval(timeout);
    //                     } else {
    //                         setPlayTime(seconds);
    //                     }
    //                 });
    //             }
    //         }, 100);
    //     });
    // };
    // 删除录音
    const handleDelAudio = async () => {
        // 初始化录音
        setRecordUri('');
        prepareRecordingPath(`${AudioUtils.DocumentDirectoryPath}/quick_audio_${new Date().getTime()}.aac`);
        setCurrentTime(0);
        setStop(false);
        setRecording(false);
        setIsExist(false);
        setPlayTime(0);
        setDuration(0);
    };
    useEffect(() => {
        if (recordUri !== '') {
            setWhoosh2(new Sound(recordUri, '', (err) => {
                if (err) {
                    Toast.info('加载音频失败', 1, undefined, false);
                }
            }));
        }
    }, [recordUri]);
    const playAudio = async (value) => {
        setDuration(whoosh2.getDuration());
        whoosh2.setCurrentTime(value);
        whoosh2.play((success) => {
            if (success) {
                Toast.info('播放完毕', 1, undefined, false);
            } else {
                Toast.info('播放失败', 1, undefined, false);
            }
        });
        const timeout = setInterval(() => {
            if (whoosh2 && whoosh2.isLoaded()) {
                whoosh2.getCurrentTime((seconds, isPlaying) => {
                    if (!isPlaying) {
                        // setPlayTime(seconds);
                        clearInterval(timeout);
                    } else {
                        setPlayTime(seconds);
                    }
                });
            }
        }, 100);
    };

    const stopAudio = () => {
        whoosh2.stop();
    };
    useImperativeHandle(ref, () => ({
        stopAudio,
    }));
    // const onSliderEditing = (value) => {
    //     const player = new Sound(recordUri !== '' ? recordUri : audioPath, '', (err) => {
    //         if (err) {
    //             Toast.info('加载音频失败', 1, undefined, false);
    //         }
    //         player.setCurrentTime(value);
    //         setPlayTime(value);
    //         player.play((success) => {
    //             if (success) {
    //                 Toast.info('播放完毕', 1, undefined, false);
    //             } else {
    //                 Toast.info('播放失败', 1, undefined, false);
    //             }
    //         });
    //         const timeout = setInterval(() => {
    //             if (player && player.isLoaded()) {
    //                 player.getCurrentTime((seconds, isPlaying) => {
    //                     if (!isPlaying) {
    //                         setPlayTime(seconds);
    //                         clearInterval(timeout);
    //                     } else {
    //                         setPlayTime(seconds);
    //                     }
    //                 });
    //             }
    //         }, 100);
    //     });
    // };
    return (
        <View>
            <View style={styles.layout}>
                {
                    !isExist && (
                        <View style={styles.play}>
                            <Text style={styles.time}>
                                {currentTimeString}
                            </Text>
                            <TouchableOpacity
                                onPress={() => {
                                    if (!recording) {
                                        handleStartAudio();
                                    } else {
                                        handleStopAudio();
                                    }
                                }

                                }
                            >

                                { recording ? (
                                    <View>
                                        <Feather
                                            name="pause-circle"
                                            size={60}
                                            color="#017BFF"
                                            style={{ paddingLeft: 10 }}
                                        />
                                        <Text style={styles.button_layout}>
                                            停止录音
                                        </Text>
                                    </View>
                                ) : (
                                    <View>
                                        <Feather
                                            name="play-circle"
                                            size={60}
                                            color="#017BFF"
                                            style={{ paddingLeft: 10 }}
                                        />
                                        <Text style={styles.button_layout}>
                                            开始录音
                                        </Text>
                                    </View>
                                )}

                            </TouchableOpacity>
                        </View>
                    )
                }
                {
                    isExist && (
                        <View style={styles.record}>
                            <WhiteSpace />
                            <View>
                                <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
                                    <Text>{playTimeString}</Text>
                                    <Text>{durationString}</Text>
                                </View>
                                <Slider
                                    style={styles.slider}
                                    // onValueChange={v => onSliderEditing(v)}
                                    onSlidingStart={(v) => {
                                        stopAudio();
                                        setPlayTime(v);
                                    }}
                                    onSlidingComplete={(v) => {
                                        // onSliderEditing(v);
                                        playAudio(v);
                                    }}
                                    value={playTime}
                                    thumbTintColor="#0E8FE7"
                                    minimumTrackTintColor="#2683ea"
                                    maximumTrackTintColor="#32BBB0"
                                    maximumValue={duration}
                                />
                            </View>
                            <WhiteSpace />
                            <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'flex-end' }}>
                                <TouchableOpacity
                                    activeOpacity={0.8}
                                    // onPress={() => handlePlayAudio()}
                                    onPress={() => playAudio(0)}
                                    style={{ marginRight: 30 }}
                                >
                                    <Feather
                                        name="play-circle"
                                        size={30}
                                        color="#017BFF"
                                        style={{ paddingLeft: 5 }}
                                    />
                                    <Text style={styles.button}> 播放 </Text>
                                </TouchableOpacity>
                                <TouchableOpacity
                                    activeOpacity={0.8}
                                    onPress={() => handleDelAudio()}
                                >
                                    <Feather
                                        name="trash-2"
                                        size={30}
                                        color="#017BFF"
                                        style={{ paddingLeft: 5 }}
                                    />
                                    <Text style={styles.button}> 删除 </Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    )
                }
            </View>
        </View>
    );
});
Recorder.defaultProps = {
    setRecordUri: () => {},
    recordUri: '',
};
Recorder.propTypes = {
    setRecordUri: PropTypes.func,
    recordUri: PropTypes.string,
};
export default Recorder;
